package com.yonyou.pmclouds.basecom.conf;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
public class YHTFilterWrapper implements Filter {
    private String name;
    private Filter filter;
    private DiworkYhtProperties properties;

    public YHTFilterWrapper(Filter filter, DiworkYhtProperties properties) {
        this.filter = filter;
        this.properties = properties;
        this.name = null;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        name = filterConfig.getFilterName();
        filter.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        long startTime = System.currentTimeMillis();
        try {
            String h = ((HttpServletRequest) request).getHeader("X-pmc-yyuap");
            // 如果是diwork
            if (properties.getDiworkDomainName() != null && StringUtils.isNotEmpty(h) && h.contains(properties.getDiworkDomainName())) {
                chain.doFilter(request, response);
            } else {
                filter.doFilter(request, response, chain);
            }
        } finally {
            log.trace("==========level is {} the method is {}, exe time is {} ", name, ((HttpServletRequest) request).getRequestURI(), System.currentTimeMillis() - startTime);

        }
    }

    @Override
    public void destroy() {
        filter.destroy();
    }
}
